//
//  Blast.m
//  Cell
//
//  Created by Orbitus on 8/16/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Blast.h"


@implementation Blast

- (void) awakeFromNib
{
	[self init];
}

- (id)init {
    self = [super init];
	id something;
    [[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(finishedBlast:) 
												 name:NSTaskDidTerminateNotification 
											   object:nil];
	NSLog(@"something %@",something);
	myBlast = nil; // This is a good time to initialize the pointer
	return self;
}

- (IBAction)TerminateBLAST:(id)sender
{
	[myBlast terminate];
}
- (IBAction)BLAST:(id)sender
{
	[[NSSound soundNamed:@"Morse"] play];

	[blastButton setTitle:@"Running..."];
	NSLog(@"Running Blast...");
    [blastButton setEnabled:NO];
	[blastRunningIndicator startAnimation:self];

	myArguments = [[NSMutableArray alloc] init];
	
	myBlast=[[NSTask alloc] init];
	pipe=[[NSPipe alloc] init];
	NSFileHandle *handle;

	myDesktopFolderPath = [myController desktopFolder];

	NSString* myOutFilePath = [myDesktopFolderPath stringByAppendingPathComponent:@"Rudy.blast"];

	int j=1;
	while ([[NSFileManager defaultManager] fileExistsAtPath:myOutFilePath] == YES)
	{
		myOutFilePath = [myDesktopFolderPath stringByAppendingPathComponent:[NSString stringWithFormat: @"Rudy%i.blast",j]];
		j++;
	}
	
	
	NSString *mySequenceFolderPath = @"/Sequences/iBioCAD/Desktop/sequence.fasta";
	blastPath = @"/UnixApps/blastcl3";
	///	blastPath = [myDesktopFolderPath stringByAppendingPathComponent:@"//blastcl3";
	[myBlast setLaunchPath:blastPath];
	[myBlast setCurrentDirectoryPath:myDesktopFolderPath];
	
	[myArguments addObject:@"-p"];
	[myArguments addObject:[programName titleOfSelectedItem]];

	[myArguments addObject:@"-d"];
	switch ([database indexOfSelectedItem]) {
		case 0:
			[myArguments addObject:@"nr"];
			break;
		case 1:
			[myArguments addObject:@"est"];
			break;
		case 2:
			[myArguments addObject:@"est_human"];
			break;
		case 3:
			[myArguments addObject:@"est_mouse"];
			break;
		case 4:
			[myArguments addObject:@"est_others"];
			break;
		case 5:
			[myArguments addObject:@"gss"];
			break;
		case 6:
			[myArguments addObject:@"htgs"];
			break;
		case 7:
			[myArguments addObject:@"pat"];
			break;
		case 8:
			[myArguments addObject:@"month"];
			break;
		case 9:
			[myArguments addObject:@"alu"];
			break;
		case 10:
			[myArguments addObject:@"sts"];
			break;
		case 11:
			[myArguments addObject:@"chromosome"];
			break;
		case 12:
			[myArguments addObject:@"UniVec"];
			break;
		case 13:
			[myArguments addObject:@"wgs"];
			break;
		case 14:
			[myArguments addObject:@"swissprot"];
			break;
		case 15:
			[myArguments addObject:@"pdb"];
			break;
	}
	
	
	 [myArguments addObject:@"-F"];
	 if([lowComplexityFilter state])
	 [myArguments addObject:@"T"];	
	 else
	 [myArguments addObject:@"F"];
	 
	 [myArguments addObject:@"-g"];
	 if([gappedAlignment state])
	 [myArguments addObject:@"T"];	
	 else
	 [myArguments addObject:@"F"];
	 
	 [myArguments addObject:@"-R"];
	 if([rpsBlastSearch state])
	 [myArguments addObject:@"T"];	
	 else
	 [myArguments addObject:@"F"];
	 
	 [myArguments addObject:@"-n"];
	 if([megaBlastSearch state])
	 [myArguments addObject:@"T"];	
	 else
	 [myArguments addObject:@"F"];
	 
	 [myArguments addObject:@"-F"];
	 if([htmlOutput state])
	 [myArguments addObject:@"T"];	
	 else
	 [myArguments addObject:@"F"];
	 
	
//	[myArguments addObject:@"-m"];
//	[myArguments addObject:[NSNumber numberWithInt:[alignmentView indexOfSelectedItem]]];
	
	[myArguments addObject:@"-i"];
	[myArguments addObject:mySequenceFolderPath];
	
	[myArguments addObject:@"-o"];
	[myArguments addObject:myOutFilePath];
	
	[myArguments addObject:@"-M"];
	[myArguments addObject:[blastMatrix titleOfSelectedItem]];
	
	if ([[programName titleOfSelectedItem] isEqualToString:@"blastx"])
	{
		[myArguments addObject:@"-Q"];
		[myArguments addObject:[NSNumber numberWithInt:([queryGeneticCodes indexOfSelectedItem]+1)]];
	}
	if ([[programName titleOfSelectedItem] isEqualToString:@"tblastx"])
	{
		[myArguments addObject:@"-D"];
		[myArguments addObject:[NSNumber numberWithInt:([databaseGeneticCodes indexOfSelectedItem]+1)]];
	}
	if ([[programName titleOfSelectedItem] isEqualToString:@"tblastn"])
	{
		[myArguments addObject:@"-q"];
		[myArguments addObject:[mismatchPenalty stringValue]];

		[myArguments addObject:@"-r"];
		[myArguments addObject:[matchReward stringValue]];
		
		[myArguments addObject:@"-G"];
		[myArguments addObject:[costToOpenGap stringValue]];

		[myArguments addObject:@"-E"];
		[myArguments addObject:[costToExtendGap stringValue]];
	}
	
	//------
	NSLog(@"Your Arguments Array = %@",myArguments);
	[blastOutput setString:[[blastOutput string] stringByAppendingString: [[myArguments description] stringByReplacingOccurrencesOfString:@"\n" withString:@""]]];
	[myBlast setArguments: myArguments];
	// [NSArray arrayWithObjects:@"-p", @"blastn", @"-d", @"nr", @"-i",
	//	   myOutFilePath ,@"-o", @"/Sequences/iBioCAD/Desktop/Rudy.blastresult", nil]];
	[myBlast setStandardOutput:pipe];
	//-p blastn -d nr -i /Sequences/iBioCAD/Desktop/sequence.fasta -o /Sequences/iBioCAD/Desktop/blastWorks.blastresult
	//	handle=[NSFileHandle fileHandleForReadingAtPath:[myBinFolderPath stringByAppendingPathComponent: @"out.fasta"]];
	
	//handle = [pipe fileHandleForReading];
	handle = [NSFileHandle fileHandleForReadingAtPath:myOutFilePath];
	[myBlast launch];
	
	[NSThread detachNewThreadSelector:@selector(copyData:)
							 toTarget:self withObject:handle];
	
//	string=[[NSString alloc] initWithData:[handle readDataToEndOfFile]
//								 encoding:NSASCIIStringEncoding]; // convert NSData -> NSString

}
- (void)copyData:(NSFileHandle*)handle {
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSData *data;
	
    while([data=[handle availableData] length]) { // until EOF (check reference)
        NSString *string=[[NSString alloc] initWithData:data
											   encoding:NSASCIIStringEncoding];
        NSRange theEnd=NSMakeRange([[blastOutput string] length],0);
		
        [blastOutput replaceCharactersInRange:theEnd
								withString:string]; // append new string to the end
        theEnd.location+=[string length]; // the end has moved
        [blastOutput scrollRangeToVisible:theEnd];
		
        [string release];
    }
	[NSThread detachNewThreadSelector:@selector(finishedBlast:)
							 toTarget:self withObject:nil];
    [pool release];
}

- (void)finishedBlast:(NSNotification *)aNotification {
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

	[blastButton setTitle:@"BLAST"];
	[blastButton setEnabled:YES];
	[blastRunningIndicator stopAnimation:self];
	int status = [myBlast terminationStatus]; 
	
	if (status == 1) 
	{
		NSLog(@"Task succeeded."); 
		[[NSSound soundNamed:@"Ping"] play];
	}
	else 
	{	
		NSLog(@"Task failed."); 
		[[NSSound soundNamed:@"Pop"] play];
	}
	
	
	NSLog(@"Blast Complete");
	
	[myBlast release]; // Don't forget to clean up memory
    [pipe release];
	[pool release];

}
@end
